<?php

class CommonApp extends Controller{

    public function _initialize() {
    	C('SHOW_PAGE_TRACE',(My::arr2var($_GET,'debug')=='true' OR C('SHOW_PAGE_TRACE')==true)?true:false);//debug调试
		//上一页面url
		define('URL_', (My::user('URL_'))?My::user('URL_'):empty($_SERVER['HTTP_REFERER'])?"":$_SERVER['HTTP_REFERER']);
    	self::setcookie();//设置相关cookie变量供前端用
    	self::commonData();
	}
	
	/**
	 * 设置相关cookie变量供前端用
	 */
	private function setcookie(){
		setcookie("__ROOT__", __ROOT__,null,__ROOT__);
		setcookie("__PROJECT__", __PROJECT__,null,'/');
	}

	/**
	 * 跳转函数(兼容函数)
	 * by huanran.zhao
	 */
	function ajaxReturn($statusCode, $message, $callbackType = '', $forwardUrl = '', $data='') {
		//404页面,使用方法$this->ajaxReturn(404,'找不到页面');
		if($statusCode==404){
			$this->assign('title',$message);
			$this->display('404');
			exit();
		}
		//ajaxsubmit方式提交的表单(表单验证方式)
		if(My::is_ajax()){
			$jsonData = array(
								'statusCode' => $statusCode,
								'message' => $message,
								'forwardUrl' => $forwardUrl,
								'data' => $data
							 );
			exit(json_encode($jsonData));
		}
		//正常方式页面跳转
		else{
			if(isset($_GET['URL'])) $URL=$_GET['URL'];//将get赋值给post
			if(isset($_POST['URL_'])) $URL_=$_POST['URL_'];//将get赋值给post
			//有传参时,强行按这个跳转url=$url
			if(!empty($url)) $URL=$URL_=$url;
			if(My::user('URL_')) $URL_=My::user('URL_');
			//默认
			if(empty($URL)) $URL = URL;
			if(empty($URL_)) $URL_ = URL_;
			
			$this->assign("text",$message);
			$this->assign("time",2);
			if($statusCode==200){
				unset($_SESSION['URL_']);
				$this->assign("url",$URL_);//成功:返回上一页面URL_
			}else{
				$_SESSION['URL_'] = $URL_;
				$this->assign("url",$URL);//失败:返回上一页面
			}
			exit(json_encode(array('statusCode'=>$statusCode,'message'=>$message)));
		}
	}

	//左菜单与面包屑
	function menu($item=''){
	    if($item=='')
	        return false;
	    $menu = array();
	    if(in_array($item,array('intro','leader','venues','student'))){
	        $menu['title'] = '学院概况';
	        $menu['app'] = 'intro';
	        $menu['act'] = 'intro';
	        $menu['submenu'] = array(
	            'intro'=>'学院简介',
	            'leader'=>'现任领导',
	            'venues'=>'场地介绍',
	            'student'=>'学生组织',
	        );
	    }else if(in_array($item,array('class','subject'))){
	        $menu['title'] = '双创学堂';
	        $menu['app'] = 'study';
	        $menu['act'] = 'class';
	        $menu['submenu'] = array(
	            'class'=>'课程学习',
	            'subject'=>'项目学习',
	        );
	    }else if(in_array($item,array('game','chair','project'))){
	        $menu['title'] = '创业活动';
	        $menu['app'] = 'activity';
	        $menu['act'] = 'game';
	        $menu['submenu'] = array(
	            'game'=>'创新创业大赛',
	            'chair'=>'创新创业讲座',
	            'project'=>'创新创业训练项目',
	            //'member'=>'会员列表',
	        );
	    }else if(in_array($item,array('country','province'))){
	        $menu['title'] = '政策法规';
	        $menu['app'] = 'policy';
	        $menu['act'] = 'country';
	        $menu['submenu'] = array(
	            'country'=>'国家政策',
	            'province'=>'省市政策',
	        );
	    }else if(in_array($item,array('train','invest','popularise','cloud'))){
	        $menu['title'] = '服务平台';
	        $menu['app'] = 'service';
	        $menu['act'] = 'train';
	        $menu['submenu'] = array(
	            'train'=>'导师培训服务',
	            'invest'=>'投资融资服务',
	            'popularise'=>'市场推广服务',
	            'cloud'=>'云平台服务',
	        );
	    }else if(in_array($item,array('event','team'))){
	        $menu['title'] = '成果展示';
	        $menu['app'] = 'result';
	        $menu['act'] = 'event';
	        $menu['submenu'] = array(
	            'event'=>'优秀创业项目展示',
	            'team'=>'优秀创业团队展示',
	        );
	    }else if(in_array($item,array('contact'))){
	        $menu['title'] = '联系我们';
	        $menu['app'] = 'contact';
	        $menu['act'] = 'index';
	    }else if($item == 'download'){
	        $menu['title'] = '下载专区';
	        $menu['app'] = 'download';
	        $menu['act'] = 'index';
	        $menu['submenu'] = array(
	            'download'=>'下载专区',
	        );
	    }else if($item == 'news'){
	    	$menu['title'] = '新闻动态';
	        $menu['app'] = 'news';
	        $menu['act'] = 'news';
	        $menu['submenu'] = array(
	            'news'=>'新闻动态',
	        );
	    }else if($item == 'announ'){
	    	$menu['title'] = '通知公告';
	        $menu['app'] = 'news';
	        $menu['act'] = 'news';
	        $menu['submenu'] = array(
	            'announ'=>'通知公告',
	        );
	    }
	    return $menu;
	}
	
	//seo
	function assign_seo($item=''){
	    if($item=='')
	        return false;
	    $alias = $item.'_seo';
	    $seo = My::alias2detail('config',$alias);
	    if(!$seo or $seo<0)
	        return false;
        $this->assign('seo_title',My::arr2var($seo,'params.seo_title'));
        $this->assign('seo_keywords',My::arr2var($seo,'params.seo_keywords'));
        $this->assign('seo_description',My::arr2var($seo,'params.seo_description'));
	}

	private function commonData(){
	    //通用数据
        $unified = My::alias2detail('config','index');
        $this->assign('unified',$unified);
	}

	//文章详情
	function detail($id=''){
        $result = My::id2detail('datas',$id,array('publish'=>1,'has_page'=>true));
        // $result['item_zh'] = DB('category')->where('item ="'.$item.'"')->field('title')->find();
        //编辑器缩略图显示
        $result['content'] = My::img_replace($result['content']);
        //防止重复刷新
        if (empty($_COOKIE['hit_id']) || $_COOKIE['hit_id'] != $id){
            setcookie('hit_id',$id,time()+600);
            ++$result['hit'];
            My::setField('datas',$id,array('key'=>'hit','value'=>$result['hit']));
        }
        $result['new'] = My::item2list('datas',$result['item'],array('publish' => 1));//最新
        $result['hit_n'] = DB('datas')->where('item ="'.$result['item'].'"')->order('hit DESC,hot DESC,id DESC')->limit('13')->field('id,title,params')->select();
        foreach ($result['hit_n'] as &$value) {
            $value['params'] = My::decodeJson($value['params']);
        }//最热
        return $result;
	}

	//分页
    function getList($item='',$pagesize='6'){
    	if($item=='')
	        return false;
        $page = I('get.page',1);
        $total = DB('datas')->where("`item`='{$item}' AND publish=1")->cache()->count();
        $result['page'] = My::page($total,array('pagesize'=>$pagesize));
        $result['data'] = My::item2list('datas',$item,array('pagesize'=>$pagesize,'page'=>$page,'publish'=>1,'order'=>'hot'));
        if(is_array($result['data']))
            foreach($result['data'] as &$value){
                //去掉html标签
                $value['content'] = trim(strip_tags(My::decodeHtml($value['content'])));
                //截取前150个字符
                $value['desc'] = mb_substr($value['content'], 0,150,'utf-8');
        }
        foreach ($result['data'] as &$value) {
            $value['times'] = floor((NOW_TIME-strtotime($value['adddate']))/86400);
        }
        return $result; 
    }
    
	/**
	 * 判断是否已登录,如未登录则跳转到登录页面
	 */
	public function checkLogin(){ //在其他扩展common控制器都能使用，这是在原有的session添加学校专业信息
	    if(!My::user('member.memberid')){
	        if(My::is_ajax())
	            $this->ajaxReturn('300','未登录!');
	        else{
	            //setCookie("history__url", $_SERVER["REQUEST_URI"], time()+31536000, "/");
	            redirect(Router::encodeUrl('index.php?app=Login'));
	        }
	    }else{
	    	if(!isset($_SESSION['member']['college_c'])){
	    		$_SESSION['member']['colleges'] = M('admin.category')->item2submenu('college',array('level'=>'1'));//找到对应学院列表
	    		$_SESSION['member']['college_c'] = $_SESSION['member']['colleges'][$_SESSION['member']['college']]['title'];//根据学院编号找到对应学院名
	    		if(!empty($_SESSION['member']['class']) && $_SESSION['member']['type'] != '0')
	    			$_SESSION['member']['class_c'] = DB('category')->where("id = {$_SESSION['member']['class']}")->getField('title');//根据专业编号找到对应专业
	    	}   //数据库查询中field()用于查询字段，field('status',ture)获取除了status之外的字段，field('id','name')获取id和name字段；getField()用于查询某个字段的值，where('id=3')->getField('name')，与field相反getField('id',true)是获取id数组，getField('id(默认第一个键名),name')获取所有id和姓名列表，getField('id,name,email',':(填分割符号)')，getField('id',3)获取id数组限制3条记录
	    	$result = $_SESSION['member'];
	    	return $result;
	    }
	}
}